package com.gjszn.kh.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gjszn.kh.dao.PhoneVerifyMapper;
import com.gjszn.kh.model.PhoneVerify;
import com.gjszn.kh.utils.PhoneCodeSender;

/**    
* @Title: PhoneVerifyService.java  
* @Package com.gjszn.kh.service    
* @author jys@nx-yt.com    
* @date 2016年1月3日 下午3:20:37  
* @version V1.0    
* @Description: TODO(用一句话描述该文件做什么)
********************************************/
@Service
public class PhoneVerifyService {
	
	@Autowired
	private PhoneVerifyMapper phoneVerifyMapper;
	
	private int maxCount = 3;
	
	public boolean add(String phone, String code){
		PhoneVerify phoneVerify = phoneVerifyMapper.selectByPrimaryKey(phone);
		if(phoneVerify != null){
			boolean b = updateGetCount(phoneVerify);
			return ( b && PhoneCodeSender.sendCode(code));
		}
		phoneVerify = new PhoneVerify();
		phoneVerify.setPhone(phone);
		phoneVerify.setCount(1);
		int result = phoneVerifyMapper.insertSelective(phoneVerify);
		if(result ==1 && PhoneCodeSender.sendCode(code)){
			return true;
		}
		return false;
	}
	
	/**
	 * 根据手机号查询是否能够获取验证码
	 * @param phone
	 * @return boolean
	 */
	public boolean isAllowedCount(String phone){
		PhoneVerify phoneVerify = phoneVerifyMapper.selectByPrimaryKey(phone);
		if(phoneVerify == null){
			return true;
		}
		if(phoneVerify.getCount() < maxCount){
			return true;
		}
		return false;
	}
	
	/**
	 * 更新phoneVerify记录，将获取验证码的次数+1
	 * @param phoneVerify
	 * @return boolean
	 */
	public boolean updateGetCount(PhoneVerify phoneVerify){
		phoneVerify.setCount(phoneVerify.getCount() + 1);
		int result = phoneVerifyMapper.updateByPrimaryKey(phoneVerify);
		if(result != 1){
			return false;
		}
		return true;
	}
	
	public void clearPhoneVerifyTable(){
		phoneVerifyMapper.clearAll();
	}

	public int getMaxCount() {
		return maxCount;
	}

	public void setMaxCount(int maxCount) {
		this.maxCount = maxCount;
	}
	
}


